// 添加调试函数
function debug(message) {
    $.writeln("[DEBUG] " + message);
}
function test() {
    var project = app.project;
    var sequence = project.activeSequence;
    debug(qe);
    var myqe = qe;
    for (var p in qe) {
        debug(p);
    }
    if (!sequence) {
        debug("没有活动序列");
        return;
    }
    var timebase = 254016000000 / sequence.timebase;
    debug(timebase);
    var selection = sequence.getSelection();
    var videoTracks = sequence.videoTracks;
    debug("videoTracks: " + videoTracks.numTracks);
    for (var i = 0; i < videoTracks.numTracks; i++) {
        var track = videoTracks[i];
        if (track.clips.numItems > 0) { 
            var firstClip = track.clips[0]; // 检查轨道上的第一个片段
            debug("firstClip: " + firstClip.name);
            // if (firstClip.mediaType === "Text") { // 字幕通常是文本类型
            //     $.writeln("找到字幕轨道：" + i);
            // }
        }
    }
    // var res = app.findCommandId("分割所有轨道");
    // debug("res: " + res);
    return;
    var frameRate = new Time();
    frameRate.setSecondsAsFraction(1, timebase);
    var minTime = Infinity;
    for (var i = 0; i < selection.length; i++) {
        var item = selection[i];
        if (item.mediaType !== "Audio" && item.mediaType !== "Video") {
            var startFrame = parseInt(item.start.getFormatted(frameRate, 109));
            debug("startFrame: " + startFrame);
            if (startFrame < minTime) {
                minTime = startFrame;
            }
        }
    }
    if (minTime === Infinity) {
        debug("没有找到字幕片段");
        return;
    } else {
        debug("最小时间: " + minTime);
    }
    var playpostion = sequence.getPlayerPosition().getFormatted(frameRate, 109);
    debug("playpostion: " + playpostion);
    var diff = parseInt(playpostion) - parseInt(minTime);
    debug("diff: " + diff);
    for (var i = 0; i < selection.length; i++) {
        var item = selection[i];
        if (item.mediaType !== "Audio" && item.mediaType !== "Video") {
            try {
                // var startFrame = item.start.getFormatted(frameRate, 109);
                // var endFrame = item.end.getFormatted(frameRate, 109);
                // debug("startFrame: " + startFrame);
                // debug("endFrame: " + endFrame);
                // var newStartFrame = parseInt(startFrame) + diff;
                // var newEndFrame = parseInt(endFrame) + diff;
                // debug("newStartFrame: " + newStartFrame);
                // debug("newEndFrame: " + newEndFrame);
                // var newStart = new Time();
                // newStart.setSecondsAsFraction(newStartFrame, timebase);
                // var newEnd = new Time();
                // newEnd.setSecondsAsFraction(newEndFrame, timebase);
                // item.start = newStart;
                // item.end = newEnd;
                var diffTime = new Time();
                diffTime.setSecondsAsFraction(diff, timebase);
                item.move(diffTime);
            } catch (error) {
                debug("错误: " + error.toString());
            }
        }
    }

    // debug("播放位置: " + playpostion);
    // var dittime = new Time();
    // dittime.setSecondsAsFraction(25, timebase);
    // sequence.setPlayerPosition(dittime.ticks.toString());
}

function moveSubtitles() {
    var project = app.project;
    var sequence = project.activeSequence;

    if (!sequence) {
        debug("没有活动序列");
        return;
    }
    var timebase = 254016000000 / sequence.timebase;
    debug(timebase);
    var selection = sequence.getSelection();
    var frameRate = new Time();
    frameRate.setSecondsAsFraction(1, timebase);
    var minTime = Infinity;
    for (var i = 0; i < selection.length; i++) {
        var item = selection[i];
        if (item.mediaType !== "Audio" && item.mediaType !== "Video") {
            var startFrame = parseInt(item.start.getFormatted(frameRate, 109));
            debug("startFrame: " + startFrame);
            if (startFrame < minTime) {
                minTime = startFrame;
            }
        }
    }
    if (minTime === Infinity) {
        debug("没有找到字幕片段");
        return;
    } else {
        debug("最小时间: " + minTime);
    }
    var playpostion = sequence.getPlayerPosition().getFormatted(frameRate, 109);
    debug("playpostion: " + playpostion);
    var diff = parseInt(playpostion) - parseInt(minTime);
    debug("diff: " + diff);
    for (var i = 0; i < selection.length; i++) {
        var item = selection[i];
        if (item.mediaType !== "Audio" && item.mediaType !== "Video") {
            try {
                var diffTime = new Time();
                diffTime.setSecondsAsFraction(diff, timebase);
                item.move(diffTime);
            } catch (error) {
                debug("错误: " + error.toString());
            }
        }
    }
}
function exportCurrentSequence(outputPath) {
    debug("开始导出序列");
    debug("输出路径: " + outputPath);

    var project = app.project;
    if (!project) {
        debug("错误：未找到项目");
        return JSON.stringify({
            success: false,
            error: "未找到项目"
        });
    }

    var sequence = project.activeSequence;
    if (!sequence) {
        debug("错误：未找到活动序列");
        return JSON.stringify({
            success: false,
            error: "未找到活动序列"
        });
    }
    var projectName = project.name;
    projectName = projectName.replace(/\.prproj/g, '');
    debug("项目名称: " + projectName);
    debug("序列名称: " + sequence.name);

    // 确保输出目录存在
    var outputFolder = new Folder(outputPath);
    if (!outputFolder.exists) {
        debug("创建输出目录: " + outputPath);
        outputFolder.create();
    }
    var name = projectName + "_" + sequence.name + "_" + new Date().getTime();
    var outputFilePath = outputPath + "/" + name + ".mp3";
    debug("完整输出路径: " + outputFilePath);

    // 检查文件是否已存在，如果存在则删除
    var existingFile = new File(outputFilePath);
    if (existingFile.exists) {
        debug("删除已存在的文件");
        existingFile.remove();
    }

    try {

        // 确定MP3预设路径
        var presetPath = "";
        // presetPath = "/Applications/Adobe Media Encoder 2025/Adobe Media Encoder 2025.app/Contents/MediaIO/systempresets/3F3F3F3F_4D503320/MP3 256kbps High Quality.epr";
        presetPath = "/Applications/Adobe Premiere Pro 2025/Adobe Premiere Pro 2025.app/Contents/MediaIO/systempresets/3F3F3F3F_4D503320/MP3 256kbps High Quality.epr";
        debug("预设路径: " + presetPath);

        // 检查预设文件是否存在
        var presetFile = new File(presetPath);
        if (!presetFile.exists) {
            debug("预设文件不存在，尝试使用替代路径");
            return JSON.stringify({
                success: false,
                error: "预设文件: " + presetPath + " 不存在"
            });
        }

        // 设置AME导出
        debug("开始导出");

        // 获取当前项目路径作为参考
        var projectPath = project.path;
        debug("项目路径: " + projectPath);


        // app.encoder.launchEncoder();
        // res = app.encoder.encodeSequence(sequence, outputFilePath, presetPath, 1, 1);
        // debug("AME 任务ID: " + res);
        res = sequence.exportAsMediaDirect(outputFilePath, presetPath, 1);

        // 检查任务是否成功添加到队列
        if (!res) {
            debug("导出失败");
            throw new Error("导出失败");
        }

        //执行任务
        // app.encoder.startBatch();
        // debug("AME批处理已启动");

        // 等待文件生成
        function waitForFile(filePath, timeoutSeconds) {
            var file = new File(filePath);
            var startTime = new Date().getTime();
            var timeout = timeoutSeconds * 1000; // 转换为毫秒
            var lastFileLength = 0;

            while (!file.exists) {
                $.sleep(500); // 等待500毫秒
                if (new Date().getTime() - startTime > timeout) {
                    return false;
                }
                lastFileLength = file.length;
            }
            while (lastFileLength !== file.length) {
                lastFileLength = file.length;
                $.sleep(1000);
            }

            // 文件存在后，等待2秒确保写入完成
            $.sleep(2000);
            return true;
        }

        // 尝试等待文件生成，最多等待3分钟
        debug("等待文件生成，最多等待3分钟...");
        var fileGenerated = waitForFile(outputFilePath, 180);

        if (fileGenerated) {
            debug("音频文件已成功生成");
            // 检查文件大小确保文件有效
            var outputFile = new File(outputFilePath);
            if (outputFile.length > 0) {
                debug("输出文件大小: " + outputFile.length + " 字节");
                return JSON.stringify({
                    success: true,
                    path: outputFilePath,
                    message: "音频导出已完成"
                });
            } else {
                debug("警告：输出文件存在但大小为0");
                return JSON.stringify({
                    success: true,
                    path: outputFilePath,
                    warning: "输出文件可能不完整，请检查"
                });
            }
        } else {
            debug("警告：等待文件生成超时");
            // 由于AME是异步的，文件可能仍在生成中
            return JSON.stringify({
                success: true,
                path: outputFilePath,
                warning: "AME导出任务已提交，但文件生成超时。请在AME中查看任务状态。"
            });
        }
    } catch (error) {
        debug("导出错误: " + error.toString());
        return JSON.stringify({
            success: false,
            error: "无法使用Adobe Media Encoder导出音频: " + error.toString()
        });
    }
}

function importSubtitles(srtPath) {
    debug("开始导入字幕...");
    try {
        var project = app.project;
        debug("获取project对象: " + (project ? "成功" : "失败"));

        if (!project) {
            return JSON.stringify({
                success: false,
                error: "无法访问project对象"
            });
        }

        var sequence = project.activeSequence;
        debug("获取activeSequence: " + (sequence ? "成功" : "失败"));

        if (!sequence) {
            return JSON.stringify({
                success: false,
                error: "没有找到活动序列"
            });
        }

        // 验证字幕文件路径
        var srtFile = new File(srtPath);
        if (!srtFile.exists) {
            debug("错误：字幕文件不存在: " + srtPath);
            return JSON.stringify({
                success: false,
                error: "字幕文件不存在: " + srtPath
            });
        }

        // 导入SRT文件
        debug("开始导入文件: " + srtPath);
        var fileName = srtPath.split(/[\/\\]/).pop();
        debug("字幕文件名: " + fileName);

        const findMediaItem = function (fileName) {
            var result = null;
            for (var i = 0; i < project.rootItem.children.numItems; i++) {
                var item = project.rootItem.children[i];
                if (item.name === fileName || item.name === fileName.replace(/\.[^\.]+$/, "")) {
                    result = item;
                    debug("找到匹配的项目: " + item.name);
                    break;
                }
            }
            return result;
        }
        var srtItem = findMediaItem(fileName);
        if (srtItem) {
            debug("找到匹配的项目: " + srtItem.name + "需要删除");
            srtItem.deleteBin();
        }
        var importSuccess = project.importFiles([srtPath]);

        debug("导入结果: " + (importSuccess ? "成功" : "失败"));

        if (!importSuccess) {
            debug("字幕导入失败");
            return JSON.stringify({
                success: false,
                error: "无法导入字幕文件，导入失败"
            });
        }

        // 导入成功后，尝试在项目中查找导入的字幕文件
        // 由于importFiles不返回导入项目的引用，需要手动查找
        debug("查找已导入的字幕文件");

        // 获取文件名（不包含路径）

        // 尝试在项目中查找匹配的项目
        var srtItem = findMediaItem(fileName);
        if (!srtItem) {
            debug("无法找到导入的字幕项目");
            return JSON.stringify({
                success: true,
                warning: "字幕文件已导入项目，但无法确定其位置，请手动添加到序列"
            });
        }

        debug("导入的字幕项目名称: " + srtItem.name);


        try {

            createSuccess = sequence.createCaptionTrack(srtItem, 0);
            if (createSuccess) {
                debug("字幕成功添加到轨道");
                return JSON.stringify({
                    success: true,
                    message: "字幕已成功导入并添加到序列"
                });
            } else {
                debug("字幕添加到轨道失败");
                return JSON.stringify({
                    success: false,
                    error: "无法将字幕添加到轨道"
                });
            }
        } catch (trackError) {
            debug("轨道操作错误: " + trackError.toString());

            // 尝试备用方法：使用项目窗口中的拖放操作
            try {
                debug("尝试备用导入方法");

                // 在Premiere中，可以尝试另一种添加方式
                var clipObject = srtItem.createSubClip(
                    srtItem.name + "_subclip",
                    0,                        // 入点时间码 
                    srtItem.getAudioDuration(), // 出点时间码
                    0,                        // 是否包含音频
                    1                         // 是否调整帧速率
                );

                if (clipObject) {
                    debug("成功创建子剪辑");
                    subtitleTrack.overwriteClip(clipObject, 0);
                    debug("使用overwriteClip方法添加字幕");

                    return JSON.stringify({
                        success: true,
                        message: "字幕已成功导入并使用备用方法添加到序列"
                    });
                } else {
                    debug("无法创建子剪辑");
                }
            } catch (altError) {
                debug("备用方法也失败: " + altError.toString());

                // 如果自动添加失败，提示用户手动添加
                debug("建议用户手动添加字幕");
                return JSON.stringify({
                    success: true,
                    warning: "字幕已导入项目，但需要手动添加到序列中",
                    error: trackError.toString()
                });
            }
        }
    } catch (error) {
        debug("导入错误: " + error.toString());
        return JSON.stringify({
            success: false,
            error: "导入错误: " + error.toString()
        });
    }
} 